const express = require('express')
const server = express()
const fs = require('fs')
const path = require('path')
const cors = require('cors')
const bodyParser = require('body-parser')

server.use(cors())
server.use(bodyParser.urlencoded({ txtended: false }))
server.use(bodyParser.json())

//获取图书列表
server.get('/api/books', (req, res) => {
    fs.readFile(path.join(__dirname, 'book.json'), (err, data) => {
        if (err) return console.log(err)
        res.send(data.toString())
    })
})



//新增图书
server.post('/api/books', (req, res) => {
    fs.readFile(path.join(__dirname, 'book.json'), (err, data) => {
        if (err) return console.log(err)
        const booklist = JSON.parse(data.toString())
        const dataBody = req.body
        dataBody.id = + booklist[0].id + 1
        booklist.unshift(dataBody)
        fs.writeFile(path.join(__dirname, 'book.json'), JSON.stringify(booklist), (err) => {
            console.log(err)
            res.send(dataBody)
        })
    })
})



//删除图书
server.delete('/api/books/:id', (req, res) => {
    fs.readFile(path.join(__dirname, 'book.json'), (err, data) => {
        if (err) return console.log(err)
        const booklist = JSON.parse(data.toString())
        const id = req.params.id
        const index = booklist.findIndex(item => item.id === +id)
        booklist.splice(index, 1)
        fs.writeFile(path.join(__dirname, 'book.json'), JSON.stringify(booklist), (err) => {
            console.log(err)
            res.send(id)
        })
    })
})



//图书详情
server.get('/api/books/:id', (req, res) => {
    fs.readFile(path.join(__dirname, 'book.json'), (err, data) => {
        if (err) return console.log(err)
        const booklist = JSON.parse(data.toString())
        const id = req.params.id
        const book = booklist.find(item => item.id === +id)
        fs.writeFile(path.join(__dirname, 'book.json'), JSON.stringify(booklist), (err) => {
            console.log(err)
            res.send(book)
        })
    })
})



//修改图书
server.put('/api/books/:id', (req, res) => {
    fs.readFile(path.join(__dirname, 'book.json'), (err, data) => {
        if (err) return console.log(err)
        const booklist = JSON.parse(data.toString())
        const id = req.params.id
        const dataBody = req.body
        const index = booklist.findIndex(item => item.id === +id)
        dataBody.id = +dataBody.id
        booklist[index] = dataBody
        fs.writeFile(path.join(__dirname, 'book.json'), JSON.stringify(booklist), (err) => {
            console.log(err)
            res.send(dataBody)
        })
    })

})
server.get('*', (req, res) => {
    res.status(404)
    res.send('请求的资源不存在')
})
server.listen(3000, () => {
    console.log('服务已启动')
})